import React, { useEffect, useState } from 'react';
import { connect, Dispatch } from 'umi';

import { Modal, message, Transfer } from 'antd';

import { WidgetsItem, PanelsItem, dashboardWidgetsItem } from '@/pages/SelfQuery/type';
import { ConnectState, IResponse } from '@/models/connect';

interface AddIndexModelProps {
  visible: boolean;
  onCancel: () => void;
  panelsItem: PanelsItem;
  widgets: Array<WidgetsItem>;
  dispatch: Dispatch;
  widgetsList: Array<dashboardWidgetsItem>;
}

const AddIndexModel: React.FC<AddIndexModelProps> = (props) => {
  const { visible, onCancel, panelsItem, widgets, dispatch, widgetsList } = props;
  const [selectWidgets, setSelectWidgets] = useState<Array<string>>([]); // 选择的指标

  // 选择指标
  const handleChange = (nextTargetKeys: Array<string>) => {
    setSelectWidgets(nextTargetKeys);
  };

  // 存储添加的指标
  const establish = () => {
    if (selectWidgets.length === 0) {
      message.warning('请选择需要添加的指标');
      return;
    }

    dispatch({
      type: 'board/saveAddWidgets',
      payload: {
        portalId: panelsItem.dashboardPortalId,
        dashboardId: panelsItem.dashboardId,
        widgets: selectWidgets,
      },
      callback: (res: IResponse) => {
        const { header } = res;
        if (header.code === 200) {
          message.success('添加指标成功');
          // 重新获取看板详情
          dispatch({
            type: 'panel/fetchDashboard',
            payload: {
              portalId: panelsItem.dashboardPortalId,
              dashboardId: panelsItem.dashboardId,
            },
          });

          onCancel();
        } else {
          message.warning('添加指标失败');
        }
      },
    });
  };

  // 获取所有的指标列表
  useEffect(() => {
    if (widgets.length === 0) {
      dispatch({
        type: 'indexLibrary/fetchDashboards',
      });
    }
  }, []);

  // 下拉选择的指标 剔除其他项目的指标
  let widgetsOption = widgets.filter((v) => v.projectId === panelsItem.projectId);
  // 剔除已添加的指标
  widgetsList.map((v) => {
    widgetsOption = widgetsOption.filter((item) => item.id !== v.widgetId);
  });

  const transferData: Array<{ key: string; title: string }> = [];

  widgetsOption.map((v) => {
    transferData.push({
      key: v.id.toString(),
      title: v.text,
    });
  });

  return (
    <Modal
      title="添加看板指标"
      destroyOnClose
      width={470}
      visible={visible}
      onOk={establish}
      onCancel={() => {
        onCancel();
      }}
    >
      <Transfer
        listStyle={{
          width: 188,
          height: 380,
        }}
        dataSource={transferData}
        titles={['全部指标', '看板指标']}
        targetKeys={selectWidgets}
        onChange={handleChange}
        // @ts-ignore
        render={(item) => item.title}
      />
    </Modal>
  );
};

export default connect(({ indexLibrary }: ConnectState) => ({
  widgets: indexLibrary.widgets,
}))(AddIndexModel);
